const { Client, GatewayIntentBits } = require('discord.js')
const db = require('../db/mysql')
const fs = require('fs')
const https = require('https')
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
})
const path = require('path')
const dotenvAbsolutePath = path.join(__dirname, '../.env')
require('dotenv').config({
  path: dotenvAbsolutePath,
})
const token = process.env.DC_BOT_TOEKN
const channelId = process.env.DC_BOT_CHANNELID

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`)
})

client.on('messageCreate', async (message) => {
  try {
    //判断频道
    if (message.channelId == channelId) {
      let strData = JSON.stringify(message.attachments)
      //判断是否返回数据
      if (strData != '[]') {
        //保存数据及图片到本地
        // 图片
        let url = JSON.parse(strData)[0].url
        let filename = JSON.parse(strData)[0].name
        // 图片信息
        let content_v = message.content.split('**')[1]
        let content_p = content_v.split(' -')[0]
        //判断是否上传图片
        let content = content_p
        if(content_p.indexOf("> ") >= 0){
          content = content_p.split('> ')[1]
        }
        // 所有json
        let jsonAll = {}
        jsonAll.body = JSON.stringify(message)
        jsonAll.info = strData
        let saveMsg = JSON.stringify(jsonAll)
        // messag名字
        let messageName = setMsgName(url)
        // await saveImage(url, filename)
        // await saveData(saveMsg)
        // 判断是否需要修改数据库
        let data = await getLastPrompt(content, message.type)
        if (data) {
          if (content == data.prompt) {
            //修改数据库
            await updateTable(data.id, url, message.id, messageName, filename)
          } else {
            console.log('名称未对应')
          }
        } else {
          console.log('数据库不存在待处理数据')
        }
      } else {
        console.log('请求数据，跳过')
      }
    } else {
      console.log('频道错误')
    }
  } catch (error) {
    let datatime = setDatetime()
    console.log('--------------' + datatime + '---------------')
    console.log(error)
  }
})

async function getLastPrompt(content, type) {
  let sql = 'select prompt, status, id from user_prompt_url where status = 1 and prompt = "' + content + '"'
  if(type === 0){
    sql += ' and type = 1 '
  }else{
    sql += ' and type = 2 '
  }
  sql += ' order by id desc limit 1'
  let res = await db.query(sql)
  if (res.length == 0) {
    return false
  } else {
    if (res[0].status != 1) {
      return false
    } else {
      return res[0]
    }
  }
}

async function saveData(msg) {
  let writeMsg = JSON.stringify(msg)
  let writeFile = path.resolve('../data/json/' + writeName() + '.json')
  fs.writeFileSync(writeFile, writeMsg, function (err) {
    if (err) {
      console.log('写入失败')
      return false
    }
  })
  console.log('文件写入完成')
}

function writeName() {
  const date = new Date() // 创建一个新的 Date 对象并传入时间戳
  const year = date.getFullYear()
  const month = padZero(date.getMonth() + 1) // JavaScript 中月份从 0 开始计数，所以需要加 1
  const day = padZero(date.getDate())
  const hour = padZero(date.getHours())
  const minute = padZero(date.getMinutes())
  const second = padZero(date.getSeconds())
  const msecond = padZero(date.getMilliseconds())

  // 拼接成 MySQL DATETIME 格式的字符串并返回
  return `${year}${month}${day}-${hour}:${minute}:${second}.${msecond}`
}
function padZero(num) {
  return num.toString().padStart(2, '0')
}

async function updateTable(id, url, mid, msgName, filename) {
  let update_at = setDatetime()
  let sql =
    'update user_prompt_url set status = 2, url = "' +
    url +
    '", filename = "' +
    filename +
    '", update_at = "' +
    update_at +
    '", message_id = "' +
    mid +
    '", message_name = "' +
    msgName +
    '" where id = ' +
    id
  await db.query(sql)
  console.log('保存数据成功')
}

async function saveImage(url, filename) {
  let writeFile = path.resolve('../data/images/' + filename)
  https
    .get(url, (response) => {
      response.pipe(fs.createWriteStream(writeFile))
    })
    .on('error', (error) => {
      console.error(error)
    })
}

function setMsgName(msgName) {
  let arr_one = msgName.split('_')
  let arr_two = arr_one[arr_one.length - 1].split('.')
  let msg = arr_two[0]
  return msg
}

function setDatetime() {
  const date = new Date() // 创建一个新的 Date 对象并传入时间戳
  const year = date.getFullYear()
  const month = padZero(date.getMonth() + 1) // JavaScript 中月份从 0 开始计数，所以需要加 1
  const day = padZero(date.getDate())
  const hour = padZero(date.getHours())
  const minute = padZero(date.getMinutes())
  const second = padZero(date.getSeconds())

  // 拼接成 MySQL DATETIME 格式的字符串并返回
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

client.login(token)
